// pages/module/order/commitOrder/commitOrder.js
import { orderSave, orderPay, orderUpdate,gift_use } from '../../../utils/imapi'
var app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    networkType: 1,
    show: 1,
    showMoney: 0,
    psd_id: '1',
    is_setAddress: 0,
    buy_user_address: '',
    buy_user_mobile: '',
    buy_user_name: '',
    address_id: '',
    data: app.globalData.cur_product_buy,
    showMask: 0,
    qustion: 0,
    agreementMask: 0,
    agreement: '',
    switchValue: 0,
    currentDay: 0,
    id: 0,
    clickAgreement: 0,
    day: 0,
    clickPay: 1,
    order_id: 0,
    part_count: 0,
    show_pay_total: 0,
    show_save_total: 0,
    fromOptions: {},
    order_remark:"",
	key:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
	var item=JSON.parse(options.item);
	console.log(item);
    
    const count = item.status;
    this.setData({
      data: item,
      part_count: count,
    })
	if(options.key){
		this.setData({
		  key:options.key
		})
	}
  },
  // 添加地址
  addAdress: function () {
    var that = this;
    var data = {};



    
    wx.chooseAddress({
      success: function (res) {
        data.userName = res.userName;
        data.postalCode = res.postalCode;
        data.provinceName = res.provinceName;
        data.cityName = res.cityName;
        data.countyName = res.countyName;
        data.detailInfo = res.detailInfo;
        data.nationalCode = res.nationalCode;
        data.telNumber = res.telNumber;
        that.setData({
          is_setAddress: 1,
          buy_user_address: res.provinceName + res.cityName + res.countyName + res.detailInfo,
          buy_user_name: res.userName,
          buy_user_mobile: res.telNumber,
          address: data
        })
		console.log(that.data.address);
      },
      fail: function (err) {

      }
    })
  },

  showMask(e) {
    var id = e.currentTarget.dataset.id;
    this.setData({
      showMask: 1,
      qustion: id
    })
  },
  // 用户协议
  agreement() {
    var that = this;
    if (that.data.agreement) {
      that.setData({
        agreementMask: 1,
      })
    } else {

    }
  },
  // 关闭弹窗
  closeMask() {
    this.setData({
      showMask: 0,
      agreementMask: 0,
    })
  },
  // 选择按钮
  switchChange(e) {
    // console.log(e);
    var val = e.detail.value ? '1' : '0'
    this.setData({
      switchValue: val
    })
  },

  // 勾选协议
  clickAgreement() {
    this.setData({
      clickAgreement: !this.data.clickAgreement
    })
  },
  // 订单支付
  async orderPay() {
    var that = this;
    if (!this.data.address) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return;
    }
	wx.showToast({title: '兑换中', icon: 'loading', duration: 10000});
    let data={
		gift_no:this.data.data.gift_no,
		name:this.data.address.userName,
		phone:this.data.address.telNumber,
		provice:this.data.address.provinceName,
		city:this.data.address.cityName,
		//counties:this.data.address.cityName,
		detailinfo:this.data.address.postalCode,
		postal_code:'',
	};
	var res=await gift_use(data);
	console.log(res);
	if(res.code === 0) {
		wx.hideToast();
		 wx.showToast({
		     title: '兑换成功',
		     icon: 'success',
		     duration: 2000//持续的时间
		   })
		   wx.navigateTo({
		     url: '/packageTab/pages/paySuccess/paySuccess?room='+JSON.stringify(this.data.address)+'&key='+JSON.stringify(this.data.key)
		   })
	}
	
  },

  async wxPay(that) {
    wx.showLoading({ title: '正在下单' })
    const sub_pid = this.data.fromOptions.sub_pid;
    console.log(this.data.address)
    const address = this.data.address;
    let data = {
      item_id: this.data.data.item_id,
      // item_id: 4,
      mchs_id: this.data.data.shop_id,
      // mchs_id: '1285496604144435201',
      spec1: this.data.data.part[0] || '',
      // spec1: 'L',
      spec2: this.data.data.part[1] || '',
      // spec2: '黄色',
      goods_amt: this.data.part_count,
      sub_pid: sub_pid,
      name: address.userName,
      phone: address.telNumber,
      provice: address.provinceName,
      city: address.cityName,
      counties: address.countyName,
      detailinfo: address.detailInfo,
      postal_code: address.postalCode
    }
    app.globalData.order_info = data;
    app.globalData.order_info.address = this.data.buy_user_address;
    const res = await orderSave(data);
    if (res.data)
      await this.pay(res.data);
  },
  async pay(orderInfo) {
    const data = {
      // price: orderInfo.price,
      price: 0.01,
      in_out: 'I',
      fin_type: 'GW',
      ref_order_no: orderInfo.order_no.toString(),
    }
    app.globalData.order_info.pay = this.data.show_pay_total;
    const res = await orderPay(data);
    wx.hideLoading();
    if (res.code === 0) {
      const data = {
        timeStamp: res.data.timestamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: () => {
          console.log('成功')
          wx.navigateTo({
            url: `/pages/module/commitOrder/paySuccess/paySuccess?room_id=${this.data.fromOptions.room_id}&custom_params=${this.data.fromOptions.custom_params}`
          })
          orderUpdate({ order_id: orderInfo.order_no.toString() })
        },
        fail: (err) => {
          console.log('失败', err)
          wx.navigateTo({
            url:`/pages/module/orderDetail/orderDetail?id=${orderInfo.order_no.toString()}`
          })
        }
      }
      wx.requestPayment(data)
    }
  },
  // 存储formid
  sendFormId(e) {
    var that = this;
    var form_id = e.detail.formId;
    var url = 'api/log/emptynull';
    var data = {
      formid: form_id
    };
    req.get(that, url, data, (res) => { })
  },
  inputEditHandler(e){
    this.setData({
      order_remark: e.detail.value
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})